package com.ruoyi.web.controller.wnjk.app;

import com.ruoyi.system.wnjk.domain.po.ShopOrder;
import com.ruoyi.system.wnjk.domain.po.ShopOrderDetail;
import com.ruoyi.system.wnjk.service.IShopItemService;
import com.ruoyi.system.wnjk.service.IShopOrderService;
import org.apache.poi.sl.draw.geom.Guide;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

import static cn.hutool.core.date.DateTime.now;

@Component
public class OrderCheckTask {

    @Autowired
    private IShopOrderService shopOrderService;

    @Autowired
    private IShopItemService shopItemService;

    /**
     * 定时任务：每5分钟检查一次未支付的订单
     */
    @Scheduled(fixedRate = 5 * 60 * 1000) // 每5分钟执行一次
    public void checkUnpaidOrders() {
        try {
            // 获取所有未支付的订单（状态为1）
            List<ShopOrder> unpaidOrders = shopOrderService.selectUnpaidOrders();
            for (ShopOrder order : unpaidOrders) {
                // 检查订单是否超时（假设超时时间为30分钟）
                Date createTime = order.getCreateTime();// 订单创建时间
                Date currentTime = now(); // 当前时间
                // 计算时间差（以分钟为单位）
                long timeDifferenceInMillis = currentTime.getTime() - createTime.getTime();
                long timeDifferenceInMinutes = timeDifferenceInMillis / (60 * 1000);

                if (timeDifferenceInMinutes>1) {
                    // 订单超时未支付，回滚库存
                    List<ShopOrderDetail> orderDetails = shopOrderService.selectOrderDetailsByOrderId(order.getId());

                    for (ShopOrderDetail detail : orderDetails) {
                        Long itemId = detail.getItemId(); // 商品ID
                        Long quantity = detail.getNum(); // 购买数量
                        // 调用商品服务，回滚库存
                        shopItemService.increaseStock(itemId, quantity);
                    }

                    // 更新订单状态为 "已取消"
                    order.setStatus(3);
                    shopOrderService.updateShopOrder(order);

                    System.out.println("订单 " + order.getId() + " 超时未支付，已取消并回滚库存");
                }else {
                    System.out.println("没有未支付超时的订单订单");
                }
            }
        } catch (Exception e) {
            System.err.println("定时任务检查未支付订单异常: " + e.getMessage());
        }
    }
}
